# cython: language_level=3
import asyncio
import os
import aioredis
import redis
from dotenv import load_dotenv

# 加载.env文件
load_dotenv(verbose=True)

redis_pool = None

def create_redis_client():
    """
    创建 Redis 客户端
    :return: Redis 客户端对象
    """
    REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
    REDIS_PORT = os.getenv("REDIS_PORT", 6379)
    REDIS_PASSWORD = os.getenv("REDIS_PASSWORD")
    REDIS_DB = os.getenv("REDIS_DB",0)
    REDIS_PREFIX = os.getenv("REDIS_PREFIX")
    REDIS_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT
    if not isinstance(REDIS_PORT, int):
        REDIS_PORT = int(REDIS_PORT) if str(REDIS_PORT).isdigit() else 6379
    if not isinstance(REDIS_DB, int):
        REDIS_DB = int(REDIS_DB) if str(REDIS_DB).isdigit() else 0
    redis_client = redis.Redis(
        host=REDIS_HOST,
        port=REDIS_PORT,
        password=REDIS_PASSWORD,
        db=REDIS_DB,
    )
    # result = redis_client.get('test')
    # print(result.decode('utf-8'))
    return redis_client

async def setup_redis(app, loop):
    REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
    REDIS_PORT = os.getenv("REDIS_PORT", 6379)
    REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", '')
    REDIS_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT
    global redis_pool
    redis_pool = await aioredis.from_url(
        REDIS_URL,
        password=REDIS_PASSWORD,
        encoding="utf-8",
        decode_responses=True)

async def close_redis(app, loop):
    global redis_pool
    redis_pool.close()
    await redis_pool.close()
    # await redis_pool.wait_closed()

async def get_redis():
    global redis_pool
    if redis_pool is None:
        raise RuntimeError("Redis is not initialized")
    return redis_pool

async def getRedisPool(loop=None):
    REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
    REDIS_PORT = os.getenv("REDIS_PORT", 6379)
    REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", '')
    REDIS_DB = os.getenv("REDIS_DB")
    REDIS_PREFIX = os.getenv("REDIS_PREFIX")
    REDIS_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT

    print("11111")

    if loop is None:
        print("222222")
        loop = asyncio.get_running_loop()

    redis_pool = aioredis.create_redis_pool(
        REDIS_URL,
        password=REDIS_PASSWORD,
        encoding="utf-8",
        decode_responses=True,
        db=REDIS_DB,
        loop=loop
    )
    
    return redis_pool

if __name__ == "__main__":
    # asyncio.run(getRedisPool())
    loop = asyncio.get_event_loop()
    redis_pool = loop.run_until_complete(getRedisPool())